import Mock from 'mockjs';

// 模拟表格数据
const data = Mock.mock({
  'list|10-50': [{
    'id|+1': 1,
    name: '@cname',
    age: '@integer(18, 60)',
    address: '@county(true)',
    checked: false,
  }]
});

Mock.mock('/api/tableData', 'get', () => {
  return {
    code: 200,
    data: data.list,
    message: 'success'
  }
});

Mock.mock('/api/tableData', 'post', (options) => {
  const body = JSON.parse(options.body);
  data.list.push({
    id: data.list.length + 1,
    name: body.name,
    age: body.age,
    address: body.address,
    checked: false,
  });
  return {
    code: 200,
    message: 'success'
  }
});

Mock.mock(/\/api\/tableData\/\d+/, 'put', (options) => {
  const id = options.url.split('/')[3];
  const body = JSON.parse(options.body);
  data.list.forEach((item:any) => {
    if (item.id === Number(id)) {
      item.name = body.name;
      item.age = body.age;
      item.address = body.address;
    }
  });
  return {
    code: 200,
    message: 'success'
  }
});

Mock.mock(/\/api\/tableData\/\d+/, 'delete', (options) => {
  const id = options.url.split('/')[3];
  data.list = data.list.filter((item:any) => item.id !== Number(id));
  return {
    code: 200,
    message: 'success'
  }
});
